<template>
  <div class="book-container">
    <!-- 搜索和操作栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" @submit.prevent>
        <el-form-item>
          <el-input
            v-model="searchForm.bookName"
            placeholder="书名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="bookName" label="书名" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="press" label="出版社" />
      <el-table-column prop="pressDate" label="出版日期" />
      <el-table-column prop="price" label="价格">
        <template #default="scope"> ¥{{ scope.row.price }} </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="书名" prop="bookName">
          <el-input v-model="form.bookName" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="出版社" prop="press">
          <el-input v-model="form.press" />
        </el-form-item>
        <el-form-item label="出版日期" prop="pressDate">
          <el-date-picker
            v-model="form.pressDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :precision="2"
            :step="0.1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getBookList, addBook, updateBook, deleteBook } from "../apis/book";

// 搜索表单
const searchForm = ref({
  bookName: "",
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const dialogTitle = computed(() =>
  dialogType.value === "add" ? "新增图书" : "编辑图书"
);

// 表单相关
const formRef = ref(null);
const form = ref({
  bookId: "",
  bookName: "",
  author: "",
  press: "",
  pressDate: "",
  price: 0,
  stock: 0,
});

// 表单校验规则
const rules = {
  bookName: [
    { required: true, message: "请输入书名", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  author: [{ required: true, message: "请输入作者", trigger: "blur" }],
  press: [{ required: true, message: "请输入出版社", trigger: "blur" }],
  pressDate: [{ required: true, message: "请选择出版日期", trigger: "change" }],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }],
  stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
};

// 获取图书列表
const getBooks = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      bookName: searchForm.value.bookName,
    };
    const res = await getBookList(params);
    tableData.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getBooks();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = { bookName: "" };
  handleSearch();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogType.value = "edit";
  form.value = {
    ...row,
    bookId: row.bookId, // 明确设置 bookId
  };
  dialogVisible.value = true;
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该图书?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteBook(row.bookId);
    ElMessage.success("删除成功");
    getBooks();
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (dialogType.value === "add") {
        await addBook(form.value);
      } else {
        await updateBook(form.value);
      }
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
      dialogVisible.value = false;
      getBooks();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    bookId: "", // 重置 bookId
    bookName: "",
    author: "",
    press: "",
    pressDate: "",
    price: 0,
    stock: 0,
  };
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getBooks();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getBooks();
};

onMounted(() => {
  getBooks();
});
</script>

<style scoped>
/* 表格滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  border-radius: 3px;
  background: rgba(144, 147, 153, 0.3);
  cursor: pointer;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: transparent;
}

/* 确保表格在容器中正确显示 */
.book-container {
  height: calc(100vh - 155px);
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

/* 分页器固定在底部 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
